import 'dart:collection';
import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:get/get.dart';
import 'package:xiongmao_clean_flutter_module/business/common/contract/persenter/contract_edit_seal_persenter.dart';
import 'package:xiongmao_clean_flutter_module/generated/add_signature_result_entity.dart';
import 'package:xiongmao_clean_flutter_module/net/http_config.dart';
import 'package:xiongmao_clean_flutter_module/res/colors.dart';
import 'package:xiongmao_clean_flutter_module/res/gaps.dart';
import 'package:xiongmao_clean_flutter_module/util/common_utils.dart';
import 'package:xiongmao_clean_flutter_module/util/toast_utils.dart';

import '../../../../mvp/base_page.dart';
import '../../../../mvp/power_presenter.dart';
import '../../../../util/log_utils.dart';
import '../../../../widgets/load_image.dart';
import '../../../../widgets/xm_webview/xm_js_msg_call.dart';
import '../../../../widgets/xm_webview/xm_web_controller.dart';
import '../../../../widgets/xm_webview/xm_webview.dart';
import '../iview/contract_edit_seal_iview.dart';


/**
 * 电子合同-印章编辑
 */
class ContractEditSealPage extends StatefulWidget {
  var companyName;

  var organization;

  var sealCdnUrl;

  var customer_id;



  @override
  _ContractEditSealPageState createState() => _ContractEditSealPageState();

  ContractEditSealPage({this.companyName,this.organization,this.sealCdnUrl,this.customer_id});
}

class _ContractEditSealPageState extends State<ContractEditSealPage> with BasePageMixin<ContractEditSealPage, PowerPresenter<dynamic>>,SingleTickerProviderStateMixin implements ContractEditSealIView {
  var _companyNameController = TextEditingController();
  var _organizationController = TextEditingController();
  late XmWebController controller;
  late ContractEditSealPresenter _presenter;

  @override
  void initState() {
    super.initState();
    _companyNameController.text = widget.companyName;
    // _organizationController.text = widget.organization;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BrnAppBar(
        title: '编辑印章样式',
      ),
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.symmetric(vertical: 20),
              color: Colours.white,child: Row(mainAxisAlignment: MainAxisAlignment.center,children: [
                LoadImage(
              widget.sealCdnUrl ?? "",
              width: 120,
              height: 120,
            )],),),
            Container(
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 16),
              height: 40,
              color: Colours.base_primary_bg_page,
              child: CommonUtils.getSimpleText("印章样式信息", 14, Colours.base_primary_text_caption),),
            BrnTextInputFormItem(
              controller: _companyNameController,
              title: "公司名称",
              isEdit: false,
              hint: "请输入",
              onChanged: (newValue) {},
            ),
            Gaps.line,
            BrnTextInputFormItem(
              controller: _organizationController,
              title: "印章编号",
              hint: "请输入",
              onChanged: (newValue) {},
            ),
            Expanded(child: Opacity(opacity: 0.0,child: XmWebView(
              onXmJsMsgCall: (XmJsMsgCall msgCall){
                var decode = json.decode(msgCall.message);
                var name = decode["name"];
                var data = decode["data"];
                switch(name){
                  case "WebViewJavascriptBridge_getCustomSealImg":
                    var url = data["url"];
                    var hashMap = HashMap<String,String>();
                    hashMap["customer_id"] = widget.customer_id;
                    hashMap["signature_img_base64"] = url;
                    _presenter.addSignature(hashMap);
                    break;
                }
                //回调id、方法名称和参数
                //controller.realController.runJavaScript("window.callBackHandle('100000')");
              },
              controllerSettingBack: (value) {
                controller = value;
                // controller.loadRequest(Uri.parse("https://m2-dev.jiazhengye.cn/sybj/contract/seals"));
                controller.loadRequest(Uri.parse("https://m2.jiazhengye.cn/sybj/contract/seals"));
                // controller.loadRequest(Uri.parse("${httpConfig.isReleaseServer()?HttpConfig.BASE_URL_M:HttpConfig.DEV_BASE_URL_M2}/sybj/contract/seals"));
              },
            ),))
          ],
        ),
      ),
      bottomNavigationBar: Container(
        height: 60,
        color: Colors.white,
        padding: EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10),
        child: BrnBigMainButton(
          bgColor: Colours.base_primary_green,
          title: '完成',
          onTap: () {
            // BrnToast.show('点击', context);
            // 创建对象
            MyObject myObject = MyObject(companyName: _companyNameController.text, number: _organizationController.text);
            // 转换为 JSON 字符串
            String jsonString = jsonEncode(myObject.toJson());
            controller.realController.runJavaScript("window.WebViewJavascriptBridgegetSealCallBack("+jsonString+")");  //切记这个字符串还得用''引住
          },
        ),
      ),
    );
  }

  @override
  PowerPresenter createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    _presenter = ContractEditSealPresenter();
    powerPresenter.requestPresenter([_presenter!]);
    return powerPresenter;
  }

  @override
  void addSignatureResultEntity(AddSignatureResultEntity data) {
    Toast.show("操作成功");
    BoostNavigator.instance.pop();
  }
}

class MyObject {
  String companyName;
  String number;

  MyObject({required this.companyName, required this.number});

  // 将对象转换为 JSON
  Map<String, dynamic> toJson() {
    return {
      'companyName': companyName,
      'number': number,
    };
  }
}
